<?php

namespace Chat\Controller;

use Think\Controller;

class IndexController extends Controller {

    public function _initialize() {
        $this->assign(I('request'));
    }
    
    public function user($sender = '18862175792', $receiver = '18916666525', $p = 1) {
        $this->assign('list', $this->getRecord($sender, $receiver, $p));
        $this->assign(compact('sender', 'receiver'));
        $this->display(IS_POST ? 'list' : '');
    }

    public function doctor($sender = '18916666525', $receiver = '18862175792', $p = 1) {
        $this->assign('list', $this->getRecord($sender, $receiver, $p));
        $this->assign(compact('sender', 'receiver'));
        $this->display(IS_POST ? 'list' : '');
    }

    public function system($sender = '18916666525',$receiver = 'system') {
        $this->assign('list', $this->getRecord($sender, 'system'));
        $this->assign(compact('sender', 'receiver'));
        $this->display();
    }

    /**
     * 获取聊天记录
     * @param string $sender
     * @param string $receiver
     * @param int $p
     * @return array 结构及
     */
    private function getRecord($sender, $receiver, $p = 1) {
        //设置为已读
        M('Chat')->where(array('sender'=>$receiver,'receiver'=>$sender,'has_read'=>'0'))->save(array('has_read'=>'1'));
        
        $where = "(sender='$sender' AND receiver='$receiver') or ( receiver='$sender' AND sender='$receiver' )";
        $list = M('Chat')->where($where)->order('id desc')->page($p, 10)->select();
        
        krsort($list);
        return $list;
    }

}
